import React from 'react';
import {CHANGE_USER_INFO} from '../../constants/userTypes';
/**
 * 加载公共组件
 * */
import MainSection from '../../components/MainSection/MainSection';
/**
 * 加载样式或图片文件
 * */
import './sass/change.scss';


class ChangeName extends React.Component {
    static contextTypes = {
        router: React.PropTypes.object.isRequired
    };
    constructor(props) {
        super(props);
        this.handleInput = this.handleInput.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.state = {
            name: ""
        };
    }

    componentDidMount() {
        const { user } = this.props;
        this.setState({
            name: user.userInfo.name
        })
    }
    handleInput(e){
        this.setState({
            name: e.target.value
        });
    }

    handleSubmit(){
        const {actions} = this.props;
        let data={
            name: this.state.name,
            colunms: 'name'
        };
        actions.changeUserInfo(data).then(res =>{
            if(res.type === CHANGE_USER_INFO){
                if(res.data.code === 20000){
                    this.context.router.goBack();
                }else{
                    alert(res.data.message)
                }
            }
        });
    }

    render() {
        let submitFlag = this.state.name.length > 0;

        return (
            <MainSection className="change" title="更改昵称">
                <div className="input-wrap">
                    <input type="text"
                           onChange={this.handleInput}
                           value={this.state.name || ''}
                           placeholder="昵称"
                           maxLength="15"/>
                </div>
                <button className={"confirm-btn " + (submitFlag ? "" : "disabled")}
                        onClick={this.handleSubmit}>确定</button>
            </MainSection>
        );
    }
}

export default ChangeName;